<template>
  <el-form
    ref="myForm"
    :model="form"
    status-icon
    :rules="rules"
    label-width="120px"
    class="myform"
  >
    <el-form-item label="账号名称" prop="account">
      <el-input
        :prefix-icon="User"
        clearable
        v-model="form.account"
        placeholder="账号名称"
        type="text"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item label="登录密码" prop="password">
      <el-input
        :prefix-icon="Lock"
        clearable
        v-model="form.password"
        placeholder="登录密码"
        show-password
        type="password"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item class="lastitem">
      <div class="alinks">
        <router-link to="/register" class="litem">去注册</router-link>
        <router-link to="/findpass" class="litem bg">忘记密码</router-link>
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="success" class="btnblock" @click="submitData()"
        >登录</el-button
      >
      <el-button type="danger" class="btnblock" @click="resetForm()"
        >重置</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { User, Lock, Iphone } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import { reg } from "@/utils/validate";
import { ElMessage } from "element-plus";
import { Ajax } from "../../api";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();

interface UserTypes {
  account: any;
  password: any;
}
const myForm = ref(); // value

const form = reactive<UserTypes>({
  account: "",
  password: "",
});

const rules = reactive<FormRules>({
  account: [
    {
      required: true,
      message: "请输入账号名称",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      pattern: reg.pwd,
      message: "请输入6-16位的数字和字母组合的密码",
      trigger: "blur",
    },
  ],
});

const resetForm = () => {
  myForm.value.resetFields();
};
const submitData = () => {
  myForm.value.validate(async (valid: boolean) => {
    if (valid) {
      //通过校验
      let res: any = await Ajax.login(form); //以用户名和密码在wh2209的数据库的users表中查找信息
      if (res.code == 200) {
        localStorage.setItem("yq_account", res.result.username); //为什么登陆成功以后没有存这些信息？
        localStorage.setItem("yq_phone", res.result.phone);
        sessionStorage.setItem("yq_token", res.token);
        router.push({ name: "main" }); //目前跳不了main，因为main没写，路由没配
      }
    } else {
      ElMessage.closeAll();
      ElMessage.error("登录数据校验失败");
    }
  });
};

onMounted(() => {
  if (route.query.username) {
    form.account = route.query.username;
  } else if (localStorage.getItem("yq_account")) {
    form.account = localStorage.getItem("yq_account");
  }
});
</script>

<style></style>
